#!/bin/sh

set -eu

x_run() {
  if [ $# -eq 0 ]; then
    x_build
    return
  fi

  case "$1" in
  b | build)
    shift
    x_build "$@"
    ;;

  *)
    logfatal "undefined command: $1"
    ;;
  esac
}

logprint() {
  echo "x.sh: $*" >&2
}

logfatal() {
  logprint "$@"
  exit 1
}

x_build() {
  opt_clear_=n

  for opt_; do
    case "$opt_" in
    -c | --clear)
      opt_clear_=y
      ;;
    *)
      logfatal "build: invalid option: $opt_"
      ;;
    esac
  done

  if [ $opt_clear_ = y ]; then
    logprint "clear before build"
    rm -rf build
  fi

  if [ ! -f build/bin/luster_st0 ]; then
    # 如果存在一个旧版本，则尝试用旧版本编译新版本。
    # 否则调用 c++ 来构建新版本。

    if [ -f build/bin/luster_st0.old ]; then
      logprint "build with old working builder"

      ./build/bin/luster_st0.old build
    else
      mkdir -p build/bin

      logprint "bootstrap build"

      c++ \
        -Dluster_CFG_BOOTSTRAP=1 \
        -g -o build/bin/luster_st0 \
        luster_alloc.cc \
        luster_build.cc \
        luster_fs.cc \
        luster_log.cc \
        luster_string.cc \
        luster_subproc.cc
    fi
  fi

  # 如果当前的版本构建成功，那么归档当前的版本到 .old
  if ./build/bin/luster_st0 build; then
    cp ./build/bin/luster_st0 ./build/bin/luster_st0.old
  else
    logfatal "latest builder can not build itself"
  fi
}

x_run "$@"
